/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Principal;


import de.centigrade.bizlaf.BizLafControl;
import de.centigrade.bizlaf.support.BizLafStyles;
import java.awt.print.PrinterException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import preparedstatement.DebugLevel;
import preparedstatement.StatementFactory;

/**
 *
 * @author Alfredo
 */
public class credito extends javax.swing.JFrame {
    Connection cn;
    PreparedStatement ps;
    ResultSet rs;
    float credito=0.0f;
    float resta=0.0f;
    float acuenta=0.0f;
    int idusu;
    String nombre;
    DefaultTableModel dtm1,dtm2;
    /**
     * Creates new form credito
     */
    public credito(int id,String nom) {
        initComponents();
        BizLafControl.get().setStyle(jPanel1, BizLafStyles.CONTAINER);
        BizLafControl.get().setStyle(restat, BizLafStyles.BADGE);
        BizLafControl.get().setStyle(jLabel5, BizLafStyles.CONTAINER_HEADER);
        idusu=id;
        nombre=nom;
        dtm1=(DefaultTableModel)jTable1.getModel();
        dtm2=(DefaultTableModel)jTable2.getModel();
        cargarDatos();
    }

   void cargarDatos(){
       try {
            ps = (PreparedStatement) local_connection.cn.prepareStatement("select sum(credito) from credito join venta on credito.folio = venta.folio where id_cliente ="+idusu+" group by id_cliente");
            rs = ps.executeQuery();
            if(rs.next())    
            credito=rs.getFloat(1);
            else credito = 0.0f;
            ps = (PreparedStatement) local_connection.cn.prepareStatement("select sum(acuenta) from abono where idusuario="+idusu);
            rs = ps.executeQuery();
            if(rs.next())  
                acuenta=rs.getFloat(1);
            resta=credito-acuenta;
          //  else resta = 0.0f;
            ps=(PreparedStatement)local_connection.cn.prepareStatement("select fecha,credito.folio,credito.credito from credito join venta on venta.folio = credito.folio where id_cliente = ? group by credito.folio");
            ps.setInt(1,idusu);
            rs=ps.executeQuery();
            ArrayList<Object[]> array = new ArrayList<Object[]>();   
            while (rs.next()) {
                Object[] columna = new Object[dtm1.getColumnCount()];
                for (int i = 0; i < columna.length; i++) {
                    columna[i] = rs.getObject(i + 1);
                }
                array.add(columna);
                //  
            }
            for (int i = 0; i < array.size(); i++) {
                dtm1.addRow(array.get(i));
            }
            ps=(PreparedStatement)local_connection.cn.prepareStatement("select fecha,acuenta from abono where idusuario = ?");
            ps.setInt(1,idusu);
            rs=ps.executeQuery();
            array = new ArrayList<Object[]>();   
            while (rs.next()) {
                Object[] columna = new Object[dtm2.getColumnCount()];
                for (int i = 0; i < columna.length; i++) {
                    columna[i] = rs.getObject(i + 1);
                }
                array.add(columna);
                //  
            }
            for (int i = 0; i < array.size(); i++) {
                dtm2.addRow(array.get(i));
            }
        } catch (SQLException ex) {
            VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
        }
            jLabel5.setText(nombre);
            restat.setText(""+(resta));
            jTextField1.setDocument(new credito.LimitadorCaracteres());
   }
   class LimitadorCaracteres extends PlainDocument {

        /**
         * Método al que llama el editor cada vez que se intenta insertar
         * caracteres. Sólo debemos verificar arg1, que es la cadena que se
         * quiere insertar en el JTextField
         */
        @Override
        public void insertString(int arg0, String arg1, AttributeSet arg2) throws BadLocationException {
            for (int i = 0; i < arg1.length(); i++) // si no es digit, volvemos
            {
               if (!(Character.isDigit(arg1.charAt(i)) || arg1.charAt(i) == '.')) {
                    return;
                } 
            }

            // Si todos son digit, insertamos el texto en el JTextField
            super.insertString(arg0, arg1, arg2);
        }
    }
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        tipoPago = new javax.swing.JComboBox();
        restat = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jButton2 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        jLabel2.setText("Cliente:");

        tipoPago.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Efectivo", "Tarjeta Credito", "Transferencia", "Cheque", "Deposito", "PayPal" }));

        restat.setText("jLabel6");

        jLabel4.setText("Resta:");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Fecha", "Folio", "Cantidad"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Fecha", "Cantidad"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(jTable2);

        jButton2.setText("Cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel3.setText("Cantidad a abonar:");

        jButton1.setText("Aceptar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel6.setText("Creditos");

        jTextField1.setText("jTextField1");

        jLabel7.setText("Abonos");

        jLabel5.setText("jLabel5");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tipoPago, 0, 128, Short.MAX_VALUE)
                        .addGap(57, 57, 57)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2)
                        .addGap(18, 18, 18))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 262, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 244, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(restat, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(116, 116, 116)
                                .addComponent(jLabel6)
                                .addGap(209, 209, 209)
                                .addComponent(jLabel7)))
                        .addContainerGap())))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel5)
                    .addComponent(jLabel4)
                    .addComponent(restat))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 122, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton1)
                        .addComponent(jButton2))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(tipoPago, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(20, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
       this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
      float  abono=0;
      Date date = new Date();
        SimpleDateFormat fecha = new SimpleDateFormat("dd/MM/yyyy");
        SimpleDateFormat hora = new SimpleDateFormat("hh:mm:ss aa");
        try{abono=Float.parseFloat(jTextField1.getText());}
        catch(Exception e){}
       new ticketAbono();
        if(jTextField1.getText()!=""){
        if(abono<=resta){
           try {
               ps =  StatementFactory.getStatement(local_connection.cn, "Insert into abono(idusuario,fecha,acuenta,sucursal,caja,tipopago)values(?,CURRENT_TIMESTAMP,?,?,?,?)",DebugLevel.ON);
                ps.setInt(1, idusu);
                ps.setFloat(2, abono);
                ps.setInt(3,VentanaPrincipal.sucursal);
                ps.setInt(4,VentanaPrincipal.caja);
                ps.setString(5,String.valueOf(tipoPago.getSelectedItem()));
                ps.execute();
                VentanaPrincipal.guardarCache(ps, "abono", true);
           ticketAbono.nombre=nombre;
           ticketAbono.recibido=abono;
           ticketAbono.saldo=resta;
           ticketAbono.fecha="" + fecha.format(date) + " " + hora.format(date);
           ps=local_connection.cn.prepareStatement("select restante,venta.folio,abono.fecha from abono join venta on venta.id_cliente = abono.idusuario join credito on venta.folio=credito.folio where venta.id_cliente = ?  and restante >0 group by credito.folio  order by folio asc");
           ps.setInt(1,idusu);
           rs=ps.executeQuery();
           while(rs.next()){
               ticketAbono.AddItem(rs.getString(3), rs.getString(2), rs.getString(1));
           }
           if(VentanaPrincipal.imprimir)
           try {

            ticketAbono.job.print();
            ticketAbono.job.print();
       // System.out.println("uno");
            ticketAbono.subCabezaLineas.clear();
            ticketAbono.nombre="";
            ticketAbono.impreso = false;
            ticketAbono.saldo=0.0f;
            ticketAbono.recibido=0.0f;

        } catch (PrinterException e) {
            System.out.println("Error de impresión: " + e);
        }
           } catch (SQLException ex) {
               VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
           }
           this.dispose();
       }
        else
            JOptionPane.showMessageDialog(null, "LA CANTIDAD A ABONAR ES MAYOR QUE LA QUE DEBE");
        }
        else this.dispose();
        
    }//GEN-LAST:event_jButton1ActionPerformed

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JLabel restat;
    private javax.swing.JComboBox tipoPago;
    // End of variables declaration//GEN-END:variables
}
